package com.tz.fruit.controller.backstage;

import com.tz.fruit.entity.Category;
import com.tz.fruit.entity.PageBean;
import com.tz.fruit.entity.Product;
import com.tz.fruit.entity.RecState;
import com.tz.fruit.service.IProductService;
import com.tz.fruit.validation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.acl.Group;
import java.util.List;

@Controller(value = "backProductController")
@RequestMapping("/backstage/product")
public class ProductController {

    @Autowired
    IProductService productService;

    /**
     * 查询符合条件的商品
     */
    @RequestMapping("/list")
    public String list(Model model,String keyWord, String recState,String categoryId, String loc, Long pageNow) {
        RecState recState2 = null;
        if(null != recState && !"all".equals(recState) && recState.trim().length()>0){
            recState2 = Enum.valueOf(RecState.class,recState);
        }
        Category category = null;
        if(null != categoryId && !"all".equals(categoryId) && categoryId.trim().length()>0){
            category = new Category();
            category.setCategoryId(Long.valueOf(categoryId));
        }
        if("all".equals(loc)){
            loc = null;
        }
        if(null == pageNow){
            pageNow = 1L;
        }
        PageBean<Product> pageBean = (PageBean<Product>) productService.findByPage(keyWord,recState2,category,loc,false,pageNow,4L);
        List<Category> categories = productService.findAllCategory(null,null);
        model.addAttribute("keyWord",keyWord);
        model.addAttribute("recState",recState);
        model.addAttribute("categoryId",categoryId);
        model.addAttribute("loc",loc);
        model.addAttribute("pageNow",pageNow);
        RecState[] recStates = RecState.values();
        model.addAttribute("categories",categories);
        model.addAttribute("recStates",recStates);
        model.addAttribute("pageBean",pageBean);
        return "/backstage/product/list";
    }

    /**
     * 跳转到编辑页面
     */
    @RequestMapping("/editPre")
    public String editPre(Model model,Long pid){
        //根据Id查询商品
        Product product = productService.findById(pid);
        //查询所有推荐类型
        RecState[] recStates = RecState.values();
        //查询所有类别
        List<Category> categories = productService.findAllCategory(null,null);
        //把对象放入request作用域
        model.addAttribute("product",product);
        model.addAttribute("recStates",recStates);
        model.addAttribute("categories",categories);
        return "/backstage/product/edit";
    }

    /**
     * 更新商品
     */
    @RequestMapping("/edit")
    public String edit(Product product ,HttpServletRequest req,MultipartFile file) throws IOException {
        if(file != null && file.getOriginalFilename().length()>0){
            //写入图片
            String path =  req.getServletContext().getRealPath("/")+"images/product/"+file.getOriginalFilename();
            file.transferTo(new File(path));
        }
        productService.update(product);
        return "redirect:list";
    }
    /**
     * 删除商品
     */
    @RequestMapping("/delete")
    public String delete(Long[] pid){
        for(int i=0;i<pid.length;i++){
            productService.delById(pid[i]);
        }
        return "redirect:list";
    }

    /**
     * 跳转到添加页面
     */
    @RequestMapping("/addPre")
    public String addPre(Model model){
        //查询所有推荐类型
        RecState[] recStates = RecState.values();
        //查询所有类别
        List<Category> categories = productService.findAllCategory(null,null);
        //把对象放入request作用域
        model.addAttribute("recStates",recStates);
        model.addAttribute("categories",categories);
        return "/backstage/product/add";
    }

    /**
     *  添加商品
     */
    @RequestMapping("/add")
    public String add(Model model, @Validated(value = {Group1.class,Group2.class,Group3.class,Group4.class,Group5.class,Group6.class,Group7.class})@ModelAttribute Product product, BindingResult bindingResult , HttpServletRequest req, MultipartFile file) throws IOException {
        if(file != null && file.getOriginalFilename().length()>0){
            //写入图片
            String path =  req.getServletContext().getRealPath("/")+"images/product/"+file.getOriginalFilename();
            file.transferTo(new File(path));
        }
        //数据回显
        if(bindingResult.hasErrors()){
            List<ObjectError> errors = bindingResult.getAllErrors();
            for (ObjectError e:errors){
                System.out.println(e.getDefaultMessage());
            }
            //把错误信息放入request作用域
            model.addAttribute("errors",errors);
            //查询所有推荐类型
            RecState[] recStates = RecState.values();
            //查询所有类别
            List<Category> categories = productService.findAllCategory(null,null);
            //把对象放入request作用域
            model.addAttribute("recStates",recStates);
            model.addAttribute("categories",categories);
            return "backstage/product/add";
        }
        productService.save(product);
        return "redirect:list";
    }

    /**
     * 检查产品编号以及产品名称是否已经存在
     */
    @RequestMapping("/checkData")
    public String checkData(String pNo, String pName,HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        if(pNo!=null && pNo.trim().length()>0 && pName!=null && pName.trim().length()>0){
            String result = "";
            //检查编号
            if(productService.findByPNo(pNo)==null){
                result += "true";
            }else{
                result += "false";
            }
            //检查名称
            if(productService.findByPName(pName)==null){
                result += ":true";
            }else{
                result += ":false";
            }
            out.print(result);
        }
        return null;
    }


    /**
     * 检查产品编号是否已经存在
     */
    @RequestMapping("/checkPNo")
    public String checkPNo(String pNo,HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        if(pNo!=null && pNo.trim().length()>0){
            //检查编号
            if(productService.findByPNo(pNo)==null){
                out.print("true");
            }else{
                out.print("false");
            }
        }
        return null;
    }



    /**
     * 检查产品名称是否已经存在
     * @param exclude 原来的pName，排除
     */
    @RequestMapping("/checkPName")
    public String checkPName(String pName,String exclude,HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        if(pName!=null && pName.trim().length()>0){
            Product product = productService.findByPName(pName);
            if(product==null){
                out.print("true");
            }else if(null != exclude && exclude.trim().length()>0){
                if(exclude.equals(product.getpName())){
                    out.print("true");
                }else{
                    out.print("false");
                }
            }else{
                out.print("false");
            }
        }
        return null;
    }


}
